# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings
from django.template import Context
from django.template.loader import get_template

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils import tz
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GET_TYPE_GATEWAY = 'https://mpay.9127pay.com/flashpay/cardinfo/KS/81c5'
_GATEWAY = 'https://mpay.9127pay.com/flashpay/payment?time={}&sign={}'
_QUERY_GATEWAY = 'https://mpay.9127pay.com/flashpay/query-card-order/KS/81c5?order_id={}'

APP_CONF = {
    'KS': {
        # 'API_KEY': '038a95f0-e791-c03f-7347-4be423a381c5',
        'API_KEY': '34507596-0fc5-a33a-3a3f-ff65c8d5a208',
    },
    'BSCP': {
        'API_KEY': '5fb1b50f-8439-d574-1306-6312c08c3df7'
    },
}

_CARD_TYPES = []


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def generate_sign(p_data, ts, key):
    '''  生成下单签名 '''
    s = '{}{}{}'.format(p_data, ts, key)
    m = hashlib.md5()
    m.update(s)
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(s, d, api_key):
    sign = d['sign']
    calculated_sign = generate_sign(s, d['time'], api_key)
    if sign != calculated_sign:
        _LOGGER.info("group_card_pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % s)


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = 'KS'
    response = requests.get(_GET_TYPE_GATEWAY)
    t = get_template('pay_gateway.html')
    d = json.loads(response.text)
    l = []
    count = 1
    for k in sorted(d.keys()):
        for j in sorted(d[k].keys()):
            for z in d[k][j]:
                z['label_id'] = 'id%s' % count
                z['radio_id'] = 'x%s' % (count + 10)
                z['radio_name'] = 'radio1%s' % (count)
                count = count + 1
                l.append(z)

    parameter_dict = OrderedDict((
        ('cardtypes', l),
        ('pay_amount', str(pay_amount)),
        ('orderId', str(pay.id)),
        ('info', info),
        ('url', '{}/pay/api/{}/group_recharge_card_pay_create/{}/'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH,
                                                                          app_id)),
    ))

    html = t.render(Context(parameter_dict))
    cache_id = redis_cache.save_html(pay.id, html)
    _LOGGER.info("group_card_pay create data: %s", settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def _get_card_type(s):
    l = s.split(',')
    return l[1], l[2]


def create_card_charge(request, app_id):
    data = dict(request.POST.iteritems())
    _LOGGER.info("group_pay create_card_charge data: %s", data)
    api_key = _get_api_key(app_id)

    try:
        extra = json.loads(data['info'])['extra']
    except:
        extra = {}
    user_info = extra.get('user_info', {})

    card_main_type, card_sub_type = _get_card_type(data['card_type'])
    p_dict = OrderedDict((
        ("merchant_id", app_id),
        ("order_id", str(data['orderId'])),
        ('notify_url', '{}/pay/api/{}/group_recharge_card_pay/{}/'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ("payment", 'cardpay'),
        ("bill_price", data['amount']),
        ("card_info", {
            "card_no": data['card_num'],
            "card_pwd": data['card_secret'],
            "card_main_type": card_main_type,
            "card_sub_type": card_sub_type,
        }),
        ("info", {
            "user_id": user_info.get('tel') or '1234',
            "device_ip": user_info.get('device_ip') or '216.250.103.13',
            "device_id": user_info.get('device_id') or 'IMEI863934039633181',
            "device_type": user_info.get('device_type') or 'android',
            "tel": user_info.get('tel') or '13009796247',
        }),

    ))
    p_data = json.dumps(p_dict, separators=(',', ':'))
    ts = tz.now_ts()
    sign = generate_sign(p_data, ts, api_key)
    headers = {'Content-type': 'application/json'}
    gate_url = _GATEWAY.format(ts, sign)
    response = requests.post(gate_url, data=p_data, headers=headers, timeout=3)
    _LOGGER.info('group_pay brefore data: %s,  %s, %s', p_data.encode('utf8'), response.text, response.url)
    order_db.fill_third_id(int(data['orderId']), json.loads(response.text)['flashid'])


# {
#     "status" : 0
# }
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    d = dict(request.GET.iteritems())
    _LOGGER.info("group_pay notify data: %s, %s", d, request.body)
    data = json.loads(request.body)
    verify_notify_sign(request.body, d, api_key)
    pay_id = data['merchant_order_id']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('group_pay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])

    if trade_status == 10000:
        trade_no = data.get('flashid')
        total_fee = float(data['payed_money'])
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee,
        }
        _LOGGER.info('group_pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pay_id = pay_order.id
    gate_url = _QUERY_GATEWAY.format(pay_order.third_id)
    response = requests.get(gate_url)
    _LOGGER.info('group_pay query rsp :%s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_no = data['FlashID']
        trade_status = int(json.loads(data['PaymentResponse'])['status'])
        total_fee = float(data['BillPrice']) / 100.0

        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 10000:
            _LOGGER.info('group_pay query order success, mch_id:%s pay_id:%s' % (
                pay_order.mch_id, pay_id))
            res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                           total_fee, trade_no, extend)
            if res:
                # async notify
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('group_pay data error, status_code: %s', response.status_code)
